﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Remoting.Contexts;

namespace BLL
{
    public abstract class BASEDALL<T> : IBaseDados<T> where T : class
    {
       protected dbMrCoisasEntidades db = new dbMrCoisasEntidades();

       
        public T InserirAtualizar(T reg)
        {
            ObjectStateEntry stateEntry = null;
            db.ObjectStateManager.TryGetObjectStateEntry(reg, out stateEntry);
            var objectSet = db.CreateObjectSet<T>();
            if (stateEntry == null || stateEntry.EntityKey.IsTemporary)
                objectSet.AddObject(reg);
            else if (stateEntry.State == EntityState.Detached)
                objectSet.Attach(reg);

            return reg;

        }

        public bool Atualizar(T reg)
        {
            throw new System.NotImplementedException();
        }

        public T Ler(int id)
        {
            throw new System.NotImplementedException();
        }

        public bool Excluir(T reg)
        {
            throw new System.NotImplementedException();
        }

        public List<T> Listar()
        {
            List<T> query = new List<T>(db.CreateQuery<T>(typeof (T).Name));
            return query;
        }

        public int QtdItens(Expression<Func<T,bool>> expr)
        {
            var query = db.CreateQuery<T>(typeof (T).Name).Where(expr);
            return query.Count();
        }

        public void Salvar()
        {
            db.SaveChanges();

        }

        
    }
}
